package com.jader.main;

import java.util.ArrayList;
import java.util.List;

import com.jader.activities.SouSuoActivity;
import com.jader.beans.Goods;
import com.jader.beans.User;
import com.jader.fragment.DingZhiFragment;
import com.jader.fragment.LunTanFragment;
import com.jader.fragment.MerchantFragment;
import com.jader.fragment.MineFragment;
import com.jader.fragment.SouYeFragment;
import com.jader.service.TendsService;
import com.jader.util.JaderApplication;
import com.jader.util.PreferenceUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements OnClickListener {

	FragmentManager manager;
	FragmentTransaction transaction;
	ImageView i1, i2, i3, i4, i5;
	TextView t1, t2, t3, t4, t5;
	RelativeLayout r1, r2, r3, r4, r5;
	// 顶部搜索栏
	List<Goods> list = new ArrayList<Goods>();
	private MenuItem menuItem;
	private long exitTime;
	private int position;

	// 需要初始化顶部菜单栏、中间的主要模块、底部导航栏
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		login();
		initData();
		tiaozhuan(position);
		initMiddle();
	}

	@Override
	protected void onResume() {
		Intent intent = new Intent(this, TendsService.class);
		startService(intent);
		super.onResume();
	}

	private void initData() {
		position = getIntent().getIntExtra("tiaozhuan", 0);
		manager = getSupportFragmentManager();

		// 初始化底部导航栏图片
		i1 = (ImageView) findViewById(R.id.sou);
		i2 = (ImageView) findViewById(R.id.shang);
		i3 = (ImageView) findViewById(R.id.lun);
		i4 = (ImageView) findViewById(R.id.ding);
		i5 = (ImageView) findViewById(R.id.wo);

		t1 = (TextView) findViewById(R.id.text_shou);
		t2 = (TextView) findViewById(R.id.text_shang);
		t3 = (TextView) findViewById(R.id.text_lun);
		t4 = (TextView) findViewById(R.id.text_ding);
		t5 = (TextView) findViewById(R.id.text_wo);

		r1 = (RelativeLayout) findViewById(R.id.rela_sou);
		r2 = (RelativeLayout) findViewById(R.id.rela_shang);
		r3 = (RelativeLayout) findViewById(R.id.rela_lun);
		r4 = (RelativeLayout) findViewById(R.id.rela_ding);
		r5 = (RelativeLayout) findViewById(R.id.rela_wo);

		// 添加监听器
		r1.setOnClickListener(this);
		r2.setOnClickListener(this);
		r3.setOnClickListener(this);
		r4.setOnClickListener(this);
		r5.setOnClickListener(this);
	}

	private void tiaozhuan(int position) {
		transaction = manager.beginTransaction();

		switch (position) {
		case 0:
			replaceFragment(transaction, 1);
			reset();
			i1.setImageResource(R.drawable.shouye_open);
			t1.setTextColor(0xffff4400);
			break;
		case 1:
			replaceFragment(transaction, 2);
			reset();
			i2.setImageResource(R.drawable.shangjia1_open);
			t2.setTextColor(0xffff4400);
			break;
		case 2:
			replaceFragment(transaction, 3);
			reset();
			i3.setImageResource(R.drawable.luntan1_open);
			t3.setTextColor(0xffff4400);
			break;
		case 3:
			replaceFragment(transaction, 4);
			reset();
			i4.setImageResource(R.drawable.dingzhi1_open);
			t4.setTextColor(0xffff4400);
			break;
		// 点击我跳转到相应界面
		case 4:
			replaceFragment(transaction, 5);
			reset();
			i5.setImageResource(R.drawable.wo1_open);
			t5.setTextColor(0xffff4400);
			break;

		default:
			break;
		}

		transaction.commit();
	}

	private void initMiddle() {
		// 动态添加中介碎片
		transaction = manager.beginTransaction();
		SouYeFragment fragment = new SouYeFragment();
		// 传值
		/*
		 * Bundle bundle = new Bundle(); bundle.putString("title", "首页");
		 * fragment.setArguments(bundle);
		 */
		transaction.replace(R.id.container, fragment);
		transaction.commit();

	}

	@Override
	public void onClick(View v) {
		// 监听所有控件单击事件,单击某一张图片，及时动态修改中间的模块
		// 动态添加中介碎片
		transaction = manager.beginTransaction();

		switch (v.getId()) {
		case R.id.rela_sou:
			replaceFragment(transaction, 1);
			reset();
			i1.setImageResource(R.drawable.shouye_open);
			t1.setTextColor(0xffff4400);
			break;
		case R.id.rela_shang:
			replaceFragment(transaction, 2);
			reset();
			i2.setImageResource(R.drawable.shangjia1_open);
			t2.setTextColor(0xffff4400);
			break;
		case R.id.rela_lun:
			replaceFragment(transaction, 3);
			reset();
			i3.setImageResource(R.drawable.luntan1_open);
			t3.setTextColor(0xffff4400);
			break;
		case R.id.rela_ding:
			replaceFragment(transaction, 4);
			reset();
			i4.setImageResource(R.drawable.dingzhi1_open);
			t4.setTextColor(0xffff4400);
			break;
		// 点击我跳转到相应界面
		case R.id.rela_wo:
			replaceFragment(transaction, 5);
			reset();
			i5.setImageResource(R.drawable.wo1_open);
			t5.setTextColor(0xffff4400);
			break;

		default:
			break;
		}

		transaction.commit();
	}

	// 所有的图片为不打开状态
	private void reset() {
		i1.setImageResource(R.drawable.shouye);
		i2.setImageResource(R.drawable.shangjia1);
		i3.setImageResource(R.drawable.luntan1);
		i4.setImageResource(R.drawable.dingzhi1);
		i5.setImageResource(R.drawable.wo1);
		t1.setTextColor(0xff6b6f79);
		t2.setTextColor(0xff6b6f79);
		t3.setTextColor(0xff6b6f79);
		t4.setTextColor(0xff6b6f79);
		t5.setTextColor(0xff6b6f79);
	}

	// 单击每一个图片替换中间碎片的方法
	private void replaceFragment(FragmentTransaction transaction, int flag) {
		Fragment fragment = null;
		// flag的值为1,2,3,4,分别表示单击了四个选项卡图标
		switch (flag) {
		case 1:
			fragment = new SouYeFragment();
			break;
		case 2:
			fragment = new MerchantFragment();
			break;
		case 3:
			fragment = new LunTanFragment();
			break;
		case 4:
			fragment = new DingZhiFragment();
			break;
		case 5:
			fragment = new MineFragment();
			break;
		default:
			break;
		}
		if (fragment != null) {
			transaction.replace(R.id.container, fragment);
		}

	}

	// 顶部搜索的跳转事件(传递一个categoryid)
	public void jump(View view) {
		Intent intent = new Intent(MainActivity.this, SouSuoActivity.class);
		startActivity(intent);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.store, menu);
		menuItem = menu.findItem(R.id.action_exits);
		menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
				startActivity(intent);
				finish();
				return false;
			}
		});
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 3000) {
				exitTime = System.currentTimeMillis();
				Toast.makeText(getApplicationContext(), "再按一次退出程序",
						Toast.LENGTH_SHORT).show();
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		switch (arg0) {
		case JaderApplication.DIANZAN_REQUESTCODE:
			replaceFragment(transaction, 3);
			reset();
			i3.setImageResource(R.drawable.luntan1_open);
			t3.setTextColor(0xffff4400);
			break;
		default:
			break;
		}

	}

	private void login() {
		Context context = getApplicationContext();
		if (!PreferenceUtil.getInstance(getApplicationContext())
				.getShareUserId().equals("")) {
			String money = PreferenceUtil.getInstance(context)
					.getShareUserMoney();
			double qian = 0;
			if (!JaderApplication.isEmpty(money)) {
				qian = Double.parseDouble(money);
			}
			final User user = new User(Integer.parseInt(PreferenceUtil
					.getInstance(context).getShareUserId()), PreferenceUtil
					.getInstance(context).getShareUserPic(), PreferenceUtil
					.getInstance(context).getShareUserPhone(), PreferenceUtil
					.getInstance(context).getSharePassWord(), PreferenceUtil
					.getInstance(context).getShareUserName(), PreferenceUtil
					.getInstance(context).getShareUserGender(), qian);
			RequestParams params = new RequestParams();
			params.addBodyParameter("type", "" + JaderApplication.USER_LOGIN);
			params.addBodyParameter("login_phone", user.getPhone());
			params.addBodyParameter("password", user.getPassword());
			String url = JaderApplication.getIP() + "/Jader/client";
			JaderApplication.httpUtils.send(HttpMethod.POST, url, params,
					new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							JaderApplication.user = user;
						}

						@Override
						public void onSuccess(ResponseInfo<String> info) {
							String result = info.result;
							if (!"null".equals(result)) {
								JaderApplication.user = user;
								PreferenceUtil.getInstance(getBaseContext())
										.setShareUserId(user.getUserid() + "");
								PreferenceUtil.getInstance(getBaseContext())
										.setShareUserName(user.getUsername());
								PreferenceUtil.getInstance(getBaseContext())
										.setSharePassWord(user.getPassword());
								PreferenceUtil.getInstance(getBaseContext())
										.setShareUserPic(user.getPicture());
								PreferenceUtil.getInstance(getBaseContext())
										.setShareUserPhone(user.getPhone());
								PreferenceUtil.getInstance(getBaseContext())
										.setShareUserGender(user.getGender());
								PreferenceUtil.getInstance(getBaseContext())
										.setShareUserMoney(user.getMoney());
							}
						}
					});
		}
	}
}
